package com.app.listdnd;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ListDnD extends ListActivity implements DndListView.DragListener, DndListView.DropListener {
    /** Called when the activity is first created. */
	private DndListView lvList;
	private EfficientAdapter mAdapter;
	private boolean isDnd = false;
	private ArrayList<String> list = new ArrayList<String>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        lvList = (DndListView) this.getListView();
        
        list.add("http://www.wopll.com/");
        list.add("http://www.wopll.com/?p=368");
        list.add("http://www.wopll.com/?page_id=2");
        list.add("http://www.wopll.com/?feed=rss2");
        list.add("http://www.wopll.com/?cat=20");
        
        mAdapter = new EfficientAdapter(this);
        setListAdapter(mAdapter);
		
        lvList.setDragListener(this);
		lvList.setDropListener(this);
    }

    
	private class EfficientAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

	public EfficientAdapter(Context context) {
		mInflater = LayoutInflater.from(context);
	}


	public int getCount() {
		return list.size();
	}

	public Object getItem(int pos) {
		return pos;
	}

	public long getItemId(int pos) {
		return pos;
	}

	public View getView(final int pos, View convertView, ViewGroup parent) {

		ViewHolder holder;

		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.simple_list_item_1, null);
			convertView.setBackgroundColor(Color.WHITE);
			holder = new ViewHolder();
			holder.item = (TextView) convertView.findViewById(android.R.id.text1);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.item.setText(list.get(pos));
		return convertView;
	}

	class ViewHolder {
		TextView item;
	}
}
    
	@Override
	public void drag(int from, int to) {
		// TODO Auto-generated method stub
		if(!isDnd){
			isDnd = true;
			Log.i("Drag and Drop : drag", "from : " + from + ", to : " + to);
		}
	}
	@Override
	public void drop(int from, int to) {
		// TODO Auto-generated method stub
		if(isDnd){
			Log.i("Drag and Drop : drop", "from : " + from + ", to : " + to);
			if(from == to)
				return;

			String item = list.remove(from);
			list.add(to, item);
			isDnd = false;
			
			mAdapter.notifyDataSetChanged();
			
			lvList.checkfordrop(to);
		}
	}
}